<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="物料名称" prop="vSpaName">
        <el-input
          v-model="queryParams.vSpaName"
          placeholder="请输入物料名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="vKind">
        <el-select
          v-model="queryParams.vKind"
          placeholder="物料类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.spa_spa_kind"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号" prop="vSpaModel">
        <el-input
          v-model="queryParams.vSpaModel"
          placeholder="请输入规格型号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="vSpaBrand">
        <el-input
          v-model="queryParams.vSpaBrand"
          placeholder="请输入品牌"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="合同编号" prop="vContractNo">
        <el-input
          v-model="queryParams.vContractNo"
          placeholder="请输入合同编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="供应商" prop="vContractNo">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >更新物料数据</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleDrawImport"
          >更新图纸数据</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="spaList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="角色编号" prop="roleId" width="120" /> -->
      <el-table-column
        label="物料名称"
        prop="vSpaName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="类型"
        prop="vKind"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.spa_spa_kind"
            :value="scope.row.vKind"
          />
        </template>
      </el-table-column>
      <el-table-column label="规格型号" prop="vSpaModel" />
      <el-table-column label="品牌" width="100px" prop="vSpaBrand" />
      <el-table-column label="供应商" width="150px" prop="supplier" />
      <el-table-column label="单位" width="100px" prop="vUnit" />
      <el-table-column label="最近采购价格" width="100px" prop="nLastPrice" />
      <el-table-column label="货期" width="75px" prop="nDays" />
      <el-table-column
        label="价格更新时间"
        align="center"
        prop="dBuy"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dBuy, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="价格有效期(天数)"
        width="100px"
        prop="nValidityDays"
      />
      <el-table-column
        label="价格有效期截止日"
        align="center"
        prop="dValidity"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dValidity, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="低库存预警" align="center" prop="isLowWarning">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_yes_no"
            :value="scope.row.isLowWarning"
          />
        </template>
      </el-table-column>
      <el-table-column label="预警数量" width="100px" prop="isLowQty" />
      <el-table-column label="备注" width="100px" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="viewPrice(scope.row)"
            >价格趋势</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="价格趋势"
      width="50%"
      :visible.sync="priceDisabled"
      v-if="priceDisabled"
    >
      <div id="viewPrice" style="height: 500px"></div>
    </el-dialog>
    <!-- 添加或修改物料信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物料名称" prop="vSpaName">
          <el-input
            v-model="form.vSpaName"
            placeholder="请输入物料名称"
            :disabled="disableForm"
          />
        </el-form-item>
        <el-form-item label="类型" prop="vKind">
          <el-select v-model="form.vKind" placeholder="物料类型" clearable>
            <el-option
              v-for="dict in dict.type.spa_spa_kind"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="vSpaModel">
          <el-input
            v-model="form.vSpaModel"
            placeholder="请输入规格型号"
            :disabled="disableForm"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="vSpaBrand">
          <el-input
            v-model="form.vSpaBrand"
            placeholder="请输入品牌"
            :disabled="disableForm"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input
            v-model="form.supplier"
            placeholder="请输入品牌"
            :disabled="disableForm"
          />
        </el-form-item>
        <el-form-item label="单位" prop="vUnit">
          <el-input v-model="form.vUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="最近采购价格" prop="nLastPrice">
          <el-input
            v-model="form.nLastPrice"
            placeholder="请输入最近采购价格"
            type="number"
          />
        </el-form-item>
        <el-form-item label="货期" prop="nDays">
          <el-input v-model="form.nDays" placeholder="请输入货期" />
        </el-form-item>
        <!-- <el-form-item label="价格更新时间" prop="dBuy">
          <el-date-picker
            v-model="form.dBuy"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="低库存预警" prop="isLowWarning">
          <el-select v-model="form.isLowWarning" clearable>
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预警数量" prop="isLowQty">
          <el-input
            v-model="form.isLowQty"
            placeholder="请输入预警数量"
            type="number"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 物料导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="uploadDraw.title"
      :visible.sync="uploadDraw.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadDraw"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="uploadDraw.headers"
        :action="uploadDraw.url"
        :disabled="uploadDraw.isUploading"
        :on-progress="handleFileUploadProgressDraw"
        :on-success="handleFileSuccessDraw"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileFormDraw">确 定</el-button>
        <el-button @click="uploadDraw.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  delSpa,
  addSpaById,
  updateSpaById,
  getSpaInfoById,
  viewPrice,
} from "@/api/buy/buy0001";
import { getToken } from "@/utils/auth";
import * as echarts from "echarts";
export default {
  name: "buy0001",
  dicts: ["sys_normal_disable", "spa_spa_kind", "sys_yes_no"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      spaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vSpaName: undefined,
        vKind: undefined,
        vSpaBrand: undefined,
        vSpaModel: undefined,
        vContractNo: undefined,
        supplier: undefined,
      },
      // 物料导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/buy/buy0001/importSpaData",
      },

      // 图纸导入参数
      uploadDraw: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/buy/buy0001/importDrawData",
      },

      rules: {
        vSpaName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
        ],
        vKind: [{ required: true, message: "类型不能为空", trigger: "blur" }],
        vSpaModel: [
          { required: true, message: "规格型号不能为空", trigger: "blur" },
        ],
        vSpaBrand: [
          { required: true, message: "品牌不能为空", trigger: "blur" },
        ],
        nLastPrice: [
          { required: true, message: "最近采购价格不能为空", trigger: "blur" },
        ],
      },
      priceDisabled: false,
      disableForm: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log("--------------------------------------");
      console.log(this.queryParams);
      list(this.queryParams).then((response) => {
        this.spaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {},
    handleExport() {},
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.iD);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      console.log("--------------------------------------");
      console.log(this.ids);
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.iD || this.ids;
      this.$modal
        .confirm("是否确认删除选中的的数据项？")
        .then(function () {
          return delSpa(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料信息";
    },

    // 表单重置
    reset() {
      this.form = {
        iD: undefined,
        vSpaName: undefined,
        vKind: undefined,
        vSpaModel: undefined,
        vSpaBrand: undefined,
        nLastPrice: undefined,
        vUnit: undefined,
        remark: undefined,
        nDays: undefined,
        supplier: undefined,
      };
      this.resetForm("form");
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.iD != undefined) {
            updateSpaById(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpaById(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      const iD = this.ids[0];
      getSpaInfoById({ iD: iD }).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料信息";
        this.disableForm = true;
      });
    },

    /** 价格趋势按钮操作 */
    viewPrice(row) {
      viewPrice(row).then((response) => {
        console.log(response);
        this.priceDisabled = true;
        let data = response.data;
        let xData = data.map((item) => {
          return item.createTime;
        });
        let yData = data.map((item) => {
          return item.nPrice;
        });
        this.$nextTick(() => {
          var chartDom = document.getElementById("viewPrice");
          var myChart = echarts.init(chartDom);
          var option;

          option = {
            tooltip: {
              pisition: "top",
              backgroundColor: "#000000",
              textStyle: {
                color: "#ffffff",
              },
              formatter: function (params) {
                console.log("tooltip", params);
                let index = params.dataIndex;
                let obj = data[index];
                return (
                  obj.createTime +
                  "<br/>" +
                  obj.nPrice +
                  "<br/>" +
                  obj.vContractNo
                );
              },
            },
            xAxis: {
              type: "category",
              data: xData,
            },
            yAxis: {
              type: "value",
              // min: Math.min(yData),
            },
            series: [
              {
                data: yData,
                type: "line",
              },
            ],
          };

          option && myChart.setOption(option);
        });
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "buy/buy0001/importTemplate",
        {},
        `物料价格数据导入模板.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 导入按钮操作 */
    handleDrawImport() {
      this.uploadDraw.title = "图纸导入";
      this.uploadDraw.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgressDraw(event, file, fileList) {
      this.uploadDraw.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccessDraw(response, file, fileList) {
      this.uploadDraw.open = false;
      this.uploadDraw.isUploading = false;
      this.$refs.uploadDraw.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileFormDraw() {
      this.$refs.uploadDraw.submit();
    },
  },
};
</script>
